package com.ge.common.utils;

import com.ge.modules.api.apiDTO.TbOrderGetDto;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.ListOrderedMap;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * json工具类
 * @Auther: LanYongLin
 * @Describotion:
 * @Date: 下午 2:23 2018/4/26 0026
 */
public class JsonUtils<T> {

    /**
     *
     * json转换map.
     * <br>详细说明
     * @param jsonStr json字符串
     * @return
     * @return Map<String,Object> 集合
     * @throws
     * @author slj
     */
    public static Map<String, Object> parseJSON2Map(String jsonStr){
        ListOrderedMap map = new ListOrderedMap();
        //最外层解析
        JSONObject json = JSONObject.fromObject(jsonStr);
        for(Object k : json.keySet()){
            Object v = json.get(k);
            //如果内层还是数组的话，继续解析
            if(v instanceof JSONArray){
                List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
                Iterator<JSONObject> it = ((JSONArray)v).iterator();
                while(it.hasNext()){
                    JSONObject json2 = it.next();
                    list.add(parseJSON2Map(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }

    /**
     * json转list对象
     * @param jsons
     * @return
     */
    public static List<TbOrderGetDto> jsonObj(String jsons){
        Gson gson = new Gson();
        List<TbOrderGetDto> persons = gson.fromJson(jsons, new TypeToken<List<TbOrderGetDto>>() {
        }.getType());
        return persons;
    }

    /**
     * json转list对象 //有问题
     * @param jsons
     * @return
     */
    public List<T> jsonToListObj(String jsons){
        Gson gson = new Gson();
        List<T> persons = gson.fromJson(jsons, new TypeToken<List<T>>() {
        }.getType());
        return persons;
    }

//    public static void main(String[] args) {
////        String json = "[{'commodityCode':1,'technicianCode':1,'commodityNumber':1," +
////                "'appointmentTime':1,'buyerMassage':1}]";
//
//        String json = "[{'commodityCode':'1','technicianCode':'201804235100','commodityNumber':1," +
//                "'appointmentTime':1524800100000,'buyerMassage':'我叫  ,我的联系电话是 '}]";
//        List<TbOrderGetDto> orderGetDtoList = new JsonUtils<TbOrderGetDto>().jsonToListObj(json);
//        System.out.println(orderGetDtoList.toString());
//    }
}
